package chapter1.socket.task.task1;

import java.io.*;
import java.util.*;
import java.net.ServerSocket;
import java.net.Socket;

/*
1:服务器上存有多个用户对象,考虑用List或者Map（对象包括用户和密码），
客户端通过socket登录(输入用户名和密码)，如果成功，输出欢迎信息，失败给出提示。
 */
public class Server {
    public static void main(String[] args) {
        HashMap<String, String> map = new HashMap<>();
        map.put("张三", "12345");
        map.put("李四", "54321");
        map.put("王五", "67899");
        Socket socket = null;
        PrintWriter out = null;
        try {
            ServerSocket server = new ServerSocket(1700);
            socket = server.accept();
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
            out.println("请输入用户名：");
            String username = in.readLine();
            out.println("请输入密码：");
            String password = in.readLine();
            if (!map.containsKey(username)) {
                out.println("用户名不存在，登录失败");
            } else {
                if (!(password.equals(map.get(username))))
                    out.println("密码错误，登录失败");
                else
                    out.println("Welcom to our website");
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (socket != null) {
                    socket.close();
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
